<?php
/**
 * | 节程 [ 节程赋能开发者，助力企业发展 ]
 * +----------------------------------------------------------------------
 *  | Copyright (c) 2020~2029 温州惊蛰网络科技有限公司 All rights reserved.
 * +----------------------------------------------------------------------
 *  | Licensed 节程并不是自由软件，未经许可不能去掉节程相关版权
 * +----------------------------------------------------------------------
 */


namespace app\shop_admin\service;

use app\madmin\model\Configuration;
use app\madmin\model\RechargeRecord;
use app\index\model\UserCash;
use app\madmin\model\User;
use app\shop_admin\model\Merchant;
use app\shop_admin\model\MerchantCash;
use app\shop_admin\model\MerchantWithdraw;
use app\utils\CheckWithdraw;
use app\utils\TrimData;
use think\Exception;

class MerchantWithdrawService
{

    private $user;

    private $serialNum;

    private $integralBalance;

    public function __construct()
    {
        global $user;
        $this->user = $user;
        $this->serialNum = md5(uniqid() . time());
        $integralBalance = Configuration::where(['type' => "integralBalance"])->value("configuration");
        if (empty($integralBalance))
            throw new Exception("未完善支付配置",HTTP_NOTACCEPT);
        $this->integralBalance = json_decode($integralBalance, true);
        if (!isset($this->integralBalance['merchant_withdraw']) || empty($this->integralBalance['merchant_withdraw']))
            throw new Exception("暂不支持提现",HTTP_NOTACCEPT);
    }

    /**
     * 提现:余额
     * @param float $amount
     * @param string $remark
     * @return array
     * @throws Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function total($amount, ?string $remark)
    {
        if (!isset($this->integralBalance['merchant_withdraw_type']) || !in_array(2, $this->integralBalance['merchant_withdraw_type']))
            throw new Exception("暂不支持提现至余额",HTTP_NOTACCEPT);

        $merchantCash = MerchantCash::find($this->user->merchant_id);

        $merchant = Merchant::find($this->user->merchant_id);

        $indexUser = User::where(['id' => $merchant->user_id])->with('wx')->find();
        if (!$indexUser) {
            throw new Exception("商户未绑定用户", HTTP_NOTACCEPT);
        }

        $indexUser = $indexUser->toArray();

        $userCash = UserCash::where(['user_id' => $indexUser['id']])->lock(true)->find();

        if ($merchantCash->recharge < $amount) {
            throw new Exception("余额不足", HTTP_NOTACCEPT);
        }
        $userCash->inc("total", $amount)
//            ->inc("recharge", $amount)
            ->update();
        $merchantCash->dec("merchant", $amount)->inc("merchant_withdraw", $amount)->update();
        $data = [
            "user_id" => $indexUser['id'],
            "base_in" => "admin",
            "source_type" => 4,
            "source" => "商户后台提现至余额:" . $this->user->id,
            "type" => 0,
            "money" => $amount,
            "remark" => $remark,
            "trade" => $this->serialNum,
            "status" =>1,
            "old_cash" => $userCash->total,
            "new_cash" => bcadd((string)$userCash->total,(string)$amount)
        ];
        RechargeRecord::create($data);

        MerchantWithdraw::create([
            "merchant_id" => $this->user->merchant_id,
            "withdraw" => $amount,
            "type" => 2,
            "status" => 1,
            'remark' => $remark,
            'serial_num' => $this->serialNum,
            'is_online' => 1
        ]);

        return [HTTP_CREATED, "提现至余额成功"];

    }

    public function findAll(array $data, int $page = 1, int $size = 10)
    {
        $admin = MerchantWithdraw::where(['merchant_id' => $this->user->merchant_id]);
        $admin = TrimData::searchDataTrim($admin, $data, ['begin_date', 'end_date']);
        $list = $admin->where($data)->order('id', 'desc')->paginate(['page' => $page, 'list_rows' => $size]);
        return [HTTP_SUCCESS, $list];
    }


    public function save($data, ?string $remark = '')
    {
        if($data['amount'] <= 0){
            throw new Exception("金额必须大于0", HTTP_NOTACCEPT);
        }
        $checkWithdraw = new CheckWithdraw($this->integralBalance);
        $serviceCharge = $checkWithdraw->merchant($data['amount']);

        $realityCash = bcsub((string)$data['amount'], (string)$serviceCharge);

        $merchantCash = MerchantCash::where(['merchant_id' => $this->user->merchant_id])
            ->lock(true)
            ->find();

//        $indexUser = User::where(['merchant_id' => $this->user->merchant_id])->with('wx')->find()->toArray();
//
//        $rechargeRecordData = [
//            "user_id" => $indexUser['id'],
//            "base_in" => "admin",
//            "source" => "商户后台提现申请:" . $this->user->id,
//            "is_online" => $data['is_online'],
//            "type" => 0,
//            "card" => isset($data['card']) ? $data['card'] : null,
//            "money" => $data['amount'],
//            "service_charge" => $serviceCharge,
//            "remark" => $remark,
//            "trade" => $this->serialNum
//        ];
        if ($merchantCash->recharge < $data['amount']) {
            throw new Exception("余额不足", HTTP_NOTACCEPT);
        }
//        RechargeRecord::create($rechargeRecordData);

        $merchantCash->dec("recharge", $data['amount'])->inc("withdraw", $data['amount'])->update();

        MerchantWithdraw::create([
            "merchant_id" => $this->user->merchant_id,
            "withdraw" => $data['amount'],
            "service_charge" => $serviceCharge,
            "is_online" => $data['is_online'],
            "type" => 1,
            "card" => isset($data['card']) ? $data['card'] : null,
            "status" => 0,
            'remark' => $remark,
            'serial_num' => $this->serialNum
        ]);

        return [HTTP_CREATED, "发起提现申请成功"];
    }


}